//
//  ZTEWatermarkView.m
//  Watermark
//
//  Created by 万伟琦 on 2018/8/2.
//  Copyright © 2018年 万伟琦. All rights reserved.
//

#import "ZODWatermarkView.h"

#define HORIZONTAL_SPACE 70//水平间距
#define VERTICAL_SPACE 110//竖直间距
//#define HORIZONTAL_SPACE 30//水平间距
//#define VERTICAL_SPACE 20//竖直间距

#define FONT_SIZE_WATER 18
#define CG_TRANSFORM_ROTATION (-M_PI_2 / 3)//旋转角度(正旋45度 || 反旋45度)

@interface ZODWatermarkView ()

@property (nonatomic, assign)   CGFloat     horizontalSpace;
@property (nonatomic, assign)   CGFloat     verticalSpace;
@property (nonatomic, assign)   CGFloat     rotationAngle;

@end

@implementation ZODWatermarkView

- (void)drawRect:(CGRect)rect {
    
    [self handleDisplayDataSourceProtocol];
    
    UIFont *font = self.markFont;
    if (!font) {
        font = [UIFont systemFontOfSize:FONT_SIZE_WATER];
    }
    UIColor *color = self.markColor;
    if (!color) {
        color = [UIColor colorWithRed:0x90/255.0 green:0x90/255.0 blue:0x90/255.0 alpha:50/255.0];
    }
    //原始image的宽高
    CGFloat viewWidth = self.frame.size.width;
    CGFloat viewHeight =self.frame.size.height;
    //sqrtLength：原始image的对角线length。在水印旋转矩阵中只要矩阵的宽高是原始image的对角线长度，无论旋转多少度都不会有空白。
    CGFloat sqrtLength = sqrt(viewWidth*viewWidth + viewHeight*viewHeight);
    //文字的属性
    NSDictionary *attr = @{
                           //设置字体大小
                           NSFontAttributeName: font,
                           //设置文字颜色
                           NSForegroundColorAttributeName :color,
                           };
    NSString *mark = self.markTitle;
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:mark attributes:attr];
    //绘制文字的宽高
    CGFloat strWidth = attrStr.size.width;
    CGFloat strHeight = attrStr.size.height;
    
    //开始旋转上下文矩阵，绘制水印文字
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //将绘制原点（0，0）调整到源image的中心
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(viewWidth/2, viewHeight/2));
    //以绘制原点为中心旋转
    CGContextConcatCTM(context, CGAffineTransformMakeRotation(self.rotationAngle));
    //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-viewWidth/2, -viewHeight/2));
    
    //计算需要绘制的列数和行数
    int horCount = sqrtLength / (strWidth + self.horizontalSpace) + 1;
    int verCount = sqrtLength / (strHeight + self.verticalSpace) + 1;
    
    //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
    CGFloat orignX = -(sqrtLength-viewWidth)/2;
    CGFloat orignY = -(sqrtLength-viewHeight)/2;
    
    //在每列绘制时X坐标叠加
    CGFloat tempOrignX = orignX;
    //在每行绘制时Y坐标叠加
    CGFloat tempOrignY = orignY;
    for (int i = 0; i < horCount * verCount; i++) {
        [mark drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attr];
        if (i % horCount == 0 && i != 0) {
            tempOrignX = orignX;
            tempOrignY += (strHeight + self.verticalSpace);
        }else{
            tempOrignX += (strWidth + self.horizontalSpace);
        }
    }
    
}

- (instancetype)initWithFrame:(CGRect)frame
                    markTitle:(NSString *)markTitle
                     markFont:(UIFont *)markFont
                    markColor:(UIColor *)markColor
                      respond:(BOOL)canRespond {
    
    if (self = [super initWithFrame:frame]) {
        _markTitle = markTitle;
        _markFont = markFont;
        _markColor = markColor;
        _canRespond = canRespond;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.canRespond) {
        return [super hitTest:point withEvent:event];
    }
    return nil;
}

- (void)handleDisplayDataSourceProtocol {
    if ([self.displayStyleDataSource respondsToSelector:@selector(zod_horizontalSpaceInWatermarkView:)]) {
        self.horizontalSpace = [self.displayStyleDataSource zod_horizontalSpaceInWatermarkView:self];
    }else {
        self.horizontalSpace = HORIZONTAL_SPACE;
    }
    if ([self.displayStyleDataSource respondsToSelector:@selector(zod_verticalSpaceInWatermarkView:)]) {
        self.verticalSpace = [self.displayStyleDataSource zod_verticalSpaceInWatermarkView:self];
    }else {
        self.verticalSpace = VERTICAL_SPACE;
    }
    if ([self.displayStyleDataSource respondsToSelector:@selector(zod_rotationAngleInWatermarkView:)]) {
        self.rotationAngle = [self.displayStyleDataSource zod_rotationAngleInWatermarkView:self];
    }else {
        self.rotationAngle = CG_TRANSFORM_ROTATION;
    }
}

@end
